
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )

ENT.GibHealth = 300
ENT.Busted = false

ENT.Car = nil

/*---------------------------------------------------------
   Name: Initialize
---------------------------------------------------------*/
function ENT:Initialize()
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )
	
	local phys = self.Entity:GetPhysicsObject()
		if (phys:IsValid()) then
		phys:Wake()
		phys:SetMass(1)
		//phys:EnableGravity(false)
	end
end

function RemoveGibs(ent)
	if ent:IsValid() then
		ent:Remove()
	end
end

function ENT:CleanUpGibs()
	timer.Simple(30, RemoveGibs, self.Entity)
	self.Busted = true
end

function ENT:OnTakeDamage( dmginfo )
	self.Entity:TakePhysicsDamage( dmginfo )

	if self.Busted == true then return end

	//self.Car.dmgcontroller:TakeHealth(dmginfo:GetDamage()/2)

	self.GibHealth = self.GibHealth - dmginfo:GetDamage()
	if self.GibHealth <= 0 then

		constraint.RemoveConstraints(self.Entity, "Weld")

		local phys = self.Entity:GetPhysicsObject()
			if (phys:IsValid()) then
			phys:Wake()
			phys:SetMass(100)
			//phys:EnableGravity(true)
		end

		self.Entity:CleanUpGibs()

		self.Busted = true
	end
end

function ENT:PhysicsCollide( data, physobj )
	physobj:SetVelocityInstantaneous( data.OurOldVelocity )

	if self.Busted == true then return end

	// How head on was the collide?
	local MoveDir = data.OurOldVelocity:Normalize()
	local Dot = MoveDir:Dot( data.HitNormal )
	if ( Dot < 0.3 ) then return end
	
	local HitSpeed = data.Speed * Dot
	
	if ( HitSpeed < 1000 ) then return end

	local phys = self.Entity:GetPhysicsObject()
		if (phys:IsValid()) then
		phys:Wake()
		phys:SetMass(100)
		//phys:EnableGravity(true)
	end
	
	constraint.RemoveConstraints(self.Entity, "Weld")

	self.Busted = true

	timer.Simple(30, RemoveGibs, self.Entity)

end

function ENT:Touch(ent)
end

function ENT:Use( activator, caller )
end

function ENT:Think()
	if self.Busted == true then return end
	if self.Car != nil then
		if !self.Car:IsValid() then
			self.Entity:Remove()
		else
			self.Entity:SetSkin(self.Car:GetSkin())
		end
	end
end

function ENT:SetCar(car)
	self.Car = car
end